import { MyModalProps } from "types/modal";
import {
  Button,
  Col,
  DatePicker,
  Divider,
  Drawer,
  Form,
  Input,
  InputNumber,
  Row,
  Select,
} from "antd";
import { useUser } from "@/hooks/useUser";
import { gutter } from "../const/keys";
import { types } from "./const";
import "react-quill-new/dist/quill.snow.css";
import { useEffect, useRef, useState } from "react";
import { addSaleLog, getSaleLogDetail } from "@/services/sale";
import { formatData } from "@/utils";
import dayjs from "dayjs";
import { useModel } from "@umijs/max";
import MyEditor, { MyQuillEditorRef } from "@/components/MyEditor";
type Props = { logId: number; data: any } & MyModalProps;
const App = (props: Props) => {
  const { logId, id, data = {}, onClose = () => {} } = props;
  const { initialState } = useModel("@@initialState");

  const editorRef = useRef<MyQuillEditorRef>(null);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const { userOptions } = useUser();
  const disabled = Boolean(!!logId);

  useEffect(() => {
    if (logId) {
      getSaleLogDetail(logId).then(async ({ data }) => {
        let { thisTime, nextPlannedTime, overdueSigningTime } = data || {};
        if (thisTime) {
          thisTime = dayjs(thisTime);
        }
        if (nextPlannedTime) {
          nextPlannedTime = dayjs(nextPlannedTime);
        }
        if (overdueSigningTime) {
          overdueSigningTime = dayjs(overdueSigningTime);
        }
        const formData = { thisTime, nextPlannedTime, overdueSigningTime };
        form.setFieldsValue({ ...data, ...formData });
        editorRef.current?.setData(data.logContent);
        editorRef.current?.setReadOnly(true);
      });
    }
  }, [logId]);
  const { currentUser } = initialState || {};

  return (
    <Drawer
      title={logId ? "日志详情" : "新增日志随手记"}
      width={1000}
      open={true}
      onClose={() => {
        onClose();
      }}
      footer={
        <Row gutter={[gutter, gutter]} justify="end">
          <Col>
            <Button
              disabled={loading}
              onClick={() => {
                onClose();
              }}
            >
              关闭
            </Button>
          </Col>
          <Col
            style={{
              display: logId ? "none" : "",
            }}
          >
            <Button
              loading={loading}
              type="primary"
              onClick={async () => {
                await form.validateFields();
                const values = form.getFieldsValue();
                let {
                  thisTime, //时间处理
                  nextPlannedTime,
                  overdueSigningTime,
                  ...rest
                } = values || "";
                if (thisTime) {
                  thisTime = thisTime?.format("YYYY-MM-DD");
                }
                if (nextPlannedTime) {
                  nextPlannedTime = nextPlannedTime?.format("YYYY-MM-DD");
                }
                if (overdueSigningTime) {
                  overdueSigningTime = overdueSigningTime?.format("YYYY-MM-DD");
                }
                const submitData = {
                  ...rest,
                  thisTime,
                  nextPlannedTime,
                  overdueSigningTime,
                  businessOpportunityId: id,
                };
                setLoading(true);
                const { success } = await addSaleLog(submitData);
                if (success) {
                  onClose(true);
                }
                setLoading(false);
              }}
            >
              保存
            </Button>
          </Col>
        </Row>
      }
    >
      <Form form={form} labelCol={{ span: 9 }}>
        <Row>
          <Col span={8}>
            <Form.Item label="项目名称">{data.opportunityName}</Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="客户干系人">
              {data.customerList?.length <= 0 ? formatData("") : null}
              {data.customerList?.map((customer: any, index: number) => {
                const key = `${index} + ${customer.associationText}`;
                return (
                  <span key={key}>
                    {index ? "、" : ""} {customer.associationText || "未知姓名"}
                  </span>
                );
              })}
            </Form.Item>
          </Col>
          <Col span={22}>
            <Divider />
            <h3>日志记录</h3>
          </Col>
          <Col span={8}>
            <Form.Item
              label="本次日期"
              name={"thisTime"}
              initialValue={dayjs()}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <DatePicker
                placeholder="请输入本次日期"
                disabled={disabled}
                style={{ width: "100%" }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="本次花费" name={"thisExpense"}>
              <Input placeholder="请输入本次花费" disabled={disabled} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="花费时间" name={"timeSpent"}>
              <Input disabled={disabled} placeholder="请输入花费时间" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="联系人" name={"contactName"}>
              <Input placeholder="请输入联系人" disabled={disabled} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="联系电话" name={"contactPhone"}>
              <Input
                placeholder="请输入联系电话"
                maxLength={11}
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="业务经理"
              name={"businessManager"}
              initialValue={currentUser?.userid}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select
                options={userOptions}
                placeholder="请选择业务经理"
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              label="日志内容"
              name={"logContent"}
              rules={[
                {
                  required: true,
                  validator(rule, value) {
                    const div = document.createElement("div");
                    div.innerHTML = value || ""; // 使用 value 而不是外部 content
                    console.log(value);
                    const text = div.textContent?.replace(/\s+/g, "");
                    if (value?.indexOf("<img") !== -1) {
                      return Promise.resolve();
                    }
                    if (text.length === 0) {
                      return Promise.reject(new Error("请输入日志内容"));
                    }
                    return Promise.resolve();
                  },
                },
              ]}
              labelCol={{
                span: 3,
              }}
            >
              <Input hidden />
              <MyEditor
                ref={editorRef}
                onChange={(value) => {
                  form.setFieldValue("logContent", value);
                }}
              />

              {/* <ReactQuill
                theme="snow"
                value={value}
                onChange={setValue}
                readOnly={disabled}
                className={[
                  styles.htmlWrap,
                  disabled ? styles.disabled : "",
                ].join(" ")}
                style={{
                  borderRadius: 5,
                  overflow: "hidden",
                  borderColor: "var(--ant-color-border)",
                }}
              /> */}
              {/* <Input.TextArea rows={4} placeholder="请输入日志内容" /> */}
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="下次计划日期" name={"nextPlannedTime"}>
              <DatePicker
                placeholder="请选择下次计划日期"
                style={{ width: "100%" }}
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="下次行动" name={"nextAction"}>
              <Input
                placeholder="请输入下次行动"
                maxLength={11}
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Divider />
            <h3>项目记录</h3>
          </Col>
          <Col span={8}>
            {/* 项目工程阶段 */}
            <Form.Item
              label="项目工程阶段"
              name={"projectStage"}
              initialValue={data.projectStage}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select
                placeholder="请选择项目工程阶段"
                options={types}
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 预估合同金额 */}
            <Form.Item
              label="预估合同金额"
              name={"estimatedContractAmount"}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <InputNumber
                placeholder="请输入预估合同金额"
                style={{ width: "100%" }}
                disabled={disabled}
                precision={2}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 成单概率 */}
            <Form.Item
              label="成单概率"
              name={"transactionProbability"}
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <InputNumber
                placeholder="请输入成单概率"
                style={{ width: "100%" }}
                min={0}
                max={100}
                disabled={disabled}
                addonAfter="%"
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            {/* 遇到的问题 */}
            <Form.Item
              label="遇到的问题"
              name={"problemsEncountered"}
              labelCol={{ span: 3 }}
            >
              <Input.TextArea
                rows={4}
                placeholder="请输入遇到的问题"
                disabled={disabled}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            {/* 预计签约日期 */}
            <Form.Item label="预计签约日期" name={"overdueSigningTime"}>
              <DatePicker
                placeholder="请选择预计签约日期"
                style={{ width: "100%" }}
                disabled={disabled}
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};
export default App;
